package com.losdun.aftersales.controller;

import com.losdun.aftersales.controller.req.WorkOrderVo;
import com.losdun.aftersales.domain.ContractOrder;
import com.losdun.aftersales.domain.Install;
import com.losdun.aftersales.domain.Repair;
import com.losdun.aftersales.enums.AftersalesTypeEnum;
import com.losdun.aftersales.enums.WorkStatusEnum;
import com.losdun.aftersales.service.IContractOrderService;
import com.losdun.aftersales.service.IInstallService;
import com.losdun.aftersales.service.IRepairService;
import com.losdun.common.annotation.Log;
import com.losdun.common.core.controller.BaseController;
import com.losdun.common.core.domain.AjaxResult;
import com.losdun.common.core.domain.entity.SysUser;
import com.losdun.common.core.page.TableDataInfo;
import com.losdun.common.enums.BusinessType;
import com.losdun.common.utils.DateUtils;
import com.losdun.common.utils.poi.ExcelUtil;
import com.losdun.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合同订单Controller
 * 
 * @author swordye
 * @date 2025-08-19
 */
@RestController
@RequestMapping("/aftersales/order")
public class ContractOrderController extends BaseController
{
    @Autowired
    private IContractOrderService contractOrderService;
    @Autowired
    private IInstallService installService;
    @Autowired
    private IRepairService repairService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询合同订单列表
     */
    @PreAuthorize("@ss.hasPermi('aftersales:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(ContractOrder contractOrder)
    {
        startPage();
        List<ContractOrder> list = contractOrderService.selectAuthOrderList(contractOrder);
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('aftersales:order:list')")
    @GetMapping("/queryInstallAndRepair")
    public AjaxResult queryInstallAndRepair(@RequestParam Long orderId) {
        List<WorkOrderVo> workOrderVos=new ArrayList<>();
        List<Install> installOrders = installService.queryOrderInstall(orderId);
        List<WorkOrderVo> list1 = installOrders.stream().sorted(Comparator.comparing(Install::getType)).map(install -> {
            WorkOrderVo workOrderVo = new WorkOrderVo();
            workOrderVo.setType(install.getType());
            workOrderVo.setTypeLabel(AftersalesTypeEnum.getLabelByValue(install.getType()));
            workOrderVo.setFinishTime(DateUtils.formatDateTime(install.getFinishTime()));
            workOrderVo.setStatusLabel(WorkStatusEnum.getLabel(install.getStatus()));
            if(install.getWorkerId()!=null){
                SysUser worker = sysUserService.selectUserById(install.getWorkerId());
                workOrderVo.setWorkerName(worker!=null?worker.getUserName():null);
                workOrderVo.setWorkerPhone(worker!=null?worker.getPhonenumber():null);
            }

            return workOrderVo;
        }).collect(Collectors.toList());
        workOrderVos.addAll(list1);
        List<Repair> repairs = repairService.queryRepairByOrderId(orderId);
        List<WorkOrderVo> list2 = repairs.stream().sorted(Comparator.comparing(Repair::getType)).map(repair -> {
            WorkOrderVo workOrderVo = new WorkOrderVo();
            workOrderVo.setType(repair.getType());
            workOrderVo.setTypeLabel(AftersalesTypeEnum.getLabelByValue(repair.getType()));
            workOrderVo.setFinishTime(DateUtils.formatDateTime(repair.getFinishTime()));
            workOrderVo.setStatusLabel(WorkStatusEnum.getLabel(repair.getStatus()));
            if(repair.getWorkerId()!=null){
                SysUser worker = sysUserService.selectUserById(repair.getWorkerId());
                workOrderVo.setWorkerName(worker!=null?worker.getUserName():null);
                workOrderVo.setWorkerPhone(worker!=null?worker.getPhonenumber():null);
            }
            return workOrderVo;
        }).collect(Collectors.toList());
        workOrderVos.addAll(list2);
        return AjaxResult.success(workOrderVos);
    }

    /**
     * 导出合同订单列表
     */
    @PreAuthorize("@ss.hasPermi('aftersales:order:export')")
    @Log(title = "合同订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContractOrder contractOrder)
    {
        List<ContractOrder> list = contractOrderService.selectAuthOrderList(contractOrder);
        ExcelUtil<ContractOrder> util = new ExcelUtil<ContractOrder>(ContractOrder.class);
        util.exportExcel(response, list, "合同订单数据");
    }

    /**
     * 获取合同订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('aftersales:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(contractOrderService.selectContractOrderById(id));
    }

    /**
     * 新增合同订单
     */
    @PreAuthorize("@ss.hasPermi('aftersales:order:add')")
    @Log(title = "合同订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContractOrder contractOrder)
    {
        contractOrder.setMember(true);
        return toAjax(contractOrderService.insertContractOrder(contractOrder));
    }

    /**
     * 修改合同订单
     */
    @PreAuthorize("@ss.hasPermi('aftersales:order:edit')")
    @Log(title = "合同订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContractOrder contractOrder)
    {
        return toAjax(contractOrderService.updateContractOrder(contractOrder));
    }

    /**
     * 删除合同订单
     */
    @PreAuthorize("@ss.hasPermi('aftersales:order:remove')")
    @Log(title = "合同订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(contractOrderService.deleteContractOrderByIds(ids));
    }


}
